/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmti.skeleton.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author : yaohk
 */
@Controller
public class FileUploadContorller {

    private final Log log = LogFactory.getLog(FileUploadContorller.class);
    
    public static final String TEMP_FILE_PATH = "tempFiles/images";
    
    public static String getTempFileRealPath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/") + "/" + TEMP_FILE_PATH + "/";
    }

    @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    public void imgUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam List<MultipartFile> file) throws IOException {
        //保存文件路径
        String realPath = getTempFileRealPath(request);
        //判断路径是否存在，不存在则创建
        File dir = new File(realPath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        String url = "";    //图片地址
        String fileName = "";
        String msg = "SUCCESS";
        int code = 0;
        List<String> data = new ArrayList<String>();
        for (MultipartFile multipartFile : file) {

            fileName = multipartFile.getOriginalFilename();
            Pattern reg = Pattern.compile("[.]jpg|png|jpeg|gif|bmp|JPG|PNG|JPEG|GIF|BMP$");
            Matcher matcher = reg.matcher(fileName);
            if (!matcher.find()) {
                msg = "文件类型不允许！";
                code = 1;
            } else {
                fileName = new Date().getTime() + "" + new Random().nextInt(1000) + fileName.substring(fileName.lastIndexOf("."), fileName.length());
                url = realPath + fileName;
                multipartFile.transferTo(new File(url));//写文件
            }
            data.add("\"" + fileName + "\"");
        }
        log.info(data.toString());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print("{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\",\"data\":" + data.toString() + "}");
    }

}
